package com.nova.android.tvlauncher.ui.dialog.base

import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType
import androidx.core.graphics.drawable.toDrawable
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.MutableLiveData
import kotlin.apply
import kotlin.jvm.java
import kotlin.jvm.javaClass

/**
 * 通用 TV 对话框基类，自动初始化 ViewBinding，适配遥控器导航和焦点管理
 */
abstract class BaseDialogFragment<VB : ViewBinding> : DialogFragment() {

    private var _binding: VB? = null
    protected val binding get() = _binding!!

    private var okAction: (() -> Unit)? = null
    private var cancleAction: (() -> Unit)? = null
    private var confirmAction: (() -> Unit)? = null

    // 👉 新增显示/隐藏监听
    private var onShowAction: (() -> Unit)? = null
    private var onDismissAction: (() -> Unit)? = null

    val textTip = MutableLiveData<String>()
    val textOK = MutableLiveData<String>()
    val textCancle = MutableLiveData<String>()
    val isShowSingleBtn = MutableLiveData<Boolean>()
    val isShowNoneBtn = MutableLiveData<Boolean>()

    // 添加受保护的属性，子类可覆盖
    protected open val dialogGravity: Int = Gravity.CENTER
    // 子类可覆盖的对话框背景，默认黑色
    protected open val dialogBackground: Drawable = Color.BLACK.toDrawable()

    // 子类可覆盖的背景模糊度，默认0.7f
    protected open val dialogDimAmount: Float = 0.7f

    // 子类可覆盖的对话框动画，默认为0（无自定义动画）
    protected open val dialogAnimation: Int = 0

    // 子类可覆盖的对话框宽度，默认WRAP_CONTENT
    protected open val dialogWidth: Int = ViewGroup.LayoutParams.WRAP_CONTENT

    // 子类可覆盖的对话框高度，默认WRAP_CONTENT
    protected open val dialogHeight: Int = ViewGroup.LayoutParams.WRAP_CONTENT

    @Suppress("UNCHECKED_CAST")
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // 通过反射获取泛型类型并调用 inflate 方法
        val vbClass = (javaClass.genericSuperclass as ParameterizedType)
            .actualTypeArguments[0] as Class<VB>
        val method = vbClass.getMethod(
            "inflate",
            LayoutInflater::class.java,
            ViewGroup::class.java,
            Boolean::class.java
        )
        _binding = method.invoke(null, inflater, container, false) as VB
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(savedInstanceState)
        setupKeyListener()
    }

    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            setBackgroundDrawable(dialogBackground) // 背景透明
            setLayout(dialogWidth, dialogHeight)
            setGravity(dialogGravity)
            setDimAmount(dialogDimAmount)
            if (dialogAnimation != 0) {
                setWindowAnimations(dialogAnimation) // 应用子类定义的动画
            }
        }
        // 👉 触发显示回调
        onShowAction?.invoke()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        cancleAction?.invoke()
        // 👉 触发隐藏回调
        onDismissAction?.invoke()
    }

    /**
     * 子类实现具体的初始化逻辑
     */
    abstract fun initView(savedInstanceState: Bundle?)


    // 👉 新增回调设置
    fun onShowAction(action: () -> Unit) {
        onShowAction = action
    }

    fun onDismissAction(action: () -> Unit) {
        onDismissAction = action
    }

    fun onOKAction(action: () -> Unit) {
        okAction = action
    }

    fun onConfirmAction(action: () -> Unit) {
        confirmAction = action
    }


    /**
     * 设置隐藏回调
     */
    fun onCancleAction(action: () -> Unit) {
        cancleAction = action
    }

    /**
     * 触发确认（OK）回调
     */
    protected fun invokeOKAction() {
        okAction?.invoke()
    }

    /**
     * 触发确认（OK）回调
     */
    protected fun invokeConfirmAction() {
        confirmAction?.invoke()
    }

    /**
     * 设置按键监听，处理遥控器事件
     */
    private fun setupKeyListener() {
        dialog?.setOnKeyListener { _, keyCode, event ->
            if (event.action == KeyEvent.ACTION_UP) {
                handleKeyEvent(keyCode, event)
            }
            false
        }
    }

    /**
     * 处理遥控器按键事件，子类可覆盖
     */
    open fun handleKeyEvent(keyCode: Int, event: KeyEvent): Boolean {
        return false
    }
}

/**
 * FragmentActivity 扩展函数，用于显示对话框
 */
inline fun <T : BaseDialogFragment<*>> FragmentActivity.showDialog(
    dialog: T,
    tag: String = dialog::class.java.simpleName,
    builderActions: T.() -> Unit
): T {
    dialog.apply(builderActions).show(supportFragmentManager, tag)
    return dialog
}

/**
 * Fragment 扩展函数，用于显示对话框
 */
inline fun <T : BaseDialogFragment<*>> Fragment.showDialog(
    dialog: T,
    tag: String = dialog::class.java.simpleName,
    builderActions: T.() -> Unit
): T {
    dialog.apply(builderActions).show(childFragmentManager, tag)
    return dialog
}
